/**
 * @author klv
 */
var CustomViewManagement = function(){
	var qslan=QS_Lang.watchlist;
    this.customviewGroup = {};
    this.customviewData = {};
    this.type = "01";
    this.defaultViewNameMap={
        "-1":qslan['extended'],"-2":qslan['intraday'],"-3":qslan['short'],"-4":qslan['portfolio']
    }
};
CustomViewManagement.prototype = {
    importDefaultCustomView:function(){
        var list = MstarData.WatchlistViews;//[ViewId || -2].slice()
        for(var o in list){
            this.customviewData[o]={};
            this.customviewData[o].cols = this.getCompleteColumnConfig(list[o]);
        }
    },
    /**
     * @return [{dataIndex: 'Name', width: '123', dataType:'', dataFormat:'', renderer:''},{}]
     * @param colInDB [{dataIndex: 'Name', width: '123'},{}]
     */
    getCompleteColumnConfig: function(colInDB){
        var cols = [];
        var col = null;
        //the col in database only has dataIndex and width
        for (var i = 0; i < colInDB.length; i++) {
            col = QS_WatchlistColumns[colInDB[i].dataIndex];
            if (col) {
                var newCol = {};
                $.extend(true, newCol, col);
                newCol.width = colInDB[i].width ? colInDB[i].width : col.width; //width form database
                cols.push(newCol);
            }
        }
        return cols;
    },
    /**
     * @return [{dataIndex: 'Name', width: '123'},{}]
     * @param completeCol [{dataIndex: 'Name', width: '123', dataType:'', dataFormat:'', renderer:''},{}]
     */
    getMinColumnConfig: function(completeCol){
        var cols = [];
        var col = null,code=null;
        for (var i = 0; i < completeCol.length; i++) {
            code=completeCol[i].dataIndex;
            col = QS_WatchlistColumns[code];//id and gkey will be removed
            if (col) {
                var newCol = {
                    dataIndex: code,
                    width: completeCol[i].width ? completeCol[i].width : null
                };
                cols.push(newCol);
            }
        }
        return cols;
    },
    getCustomviewData: function(id, callback){
		if(parseInt(id)<0&&!this.customviewData[id]){
			this.importDefaultCustomView();
		}
        if (!this.customviewData[id]) {
            var self = this;
			with({"currentID":id}){
				DBHelper.getWidgetTemplate(currentID, function(d){
					var obj = null;
					if (d != '') {
						obj = $.evalJSON(d);                   
						var cols = self.getCompleteColumnConfig(obj.cols); // convert to the column object.  
						for(var i=0;i<cols.length;i++){  // remove the "del" row for old saved profile.
							if(cols[i].dataIndex=="remove"){
								cols.splice(i,1);
								i--;
							}
						}
						self.customviewData[currentID] = {
							cols: cols,
							title: obj.title || self.getViewName(currentID)
						};
						
						if (typeof callback == 'function') {
							callback({"id":currentID,"data":self.customviewData[currentID]});
						}
						return {"id":currentID,data:self.customviewData[currentID]};
					}else {
						var defaultid=typeof Terminal!='undefined'?Terminal.getConfig('WatchlistDefaultView'):"-2";
						if (typeof callback == 'function') {
							self.getCustomviewData(defaultid,callback);
						}
					}
				});
			}
        }else {
            if (typeof callback == 'function') {
                callback({id:id,data:this.customviewData[id]});
            }
			return {id:id,data:this.customviewData[id]};
        }
    },
	checkName:function(name){//for sharing
        var flag=true,custom=null;    
		for(var i=GOLBAL_DATA.widgetTemplateList[this.type].length-1;i>=0;i--){
			custom=GOLBAL_DATA.widgetTemplateList[this.type][i];
			if(custom.title==$.trim(name)){
				flag = false;
				break;
			}
		}
        return flag;
    },
	getShareViewMaxIndex:function(name){//for sharing
		var temp="",custom=null,index=0,reg= /^Share:(.*)\_(\d*)(?=$)/;
		for(var i=GOLBAL_DATA.widgetTemplateList[this.type].length-1;i>=0;i--){
			custom=GOLBAL_DATA.widgetTemplateList[this.type][i],temp = reg.exec(custom.title);
			if(temp&&temp.length==3){
				if(temp[1]==$.trim(name)&&!isNaN(temp[2])){
					index=Math.max(index,temp[2]);
				}
			}
		}
        return index;
	},
    getColumnAttrFromCache: function(viewId, colKey, attr){
		var returnValue=null;
        if (this.customviewData[viewId]) {
            var cols = this.customviewData[viewId].cols;
            for (var i = 0; i < cols.length; i++) {
                col = cols[i];
                if (cols[i].dataIndex == colKey) {
                    returnValue = cols[i][attr] ? cols[i][attr] : null;
					break;
                }
            }
        }
		if(!returnValue){
			returnValue=QS_WatchlistColumns[colKey][attr];
		}
		return returnValue;
    },
    getViewName: function(id){
        if(!isNaN(id)&&id<=0){
            return this.defaultViewNameMap[id];
        }
        for (var i = 0, l = GOLBAL_DATA.widgetTemplateList[this.type].length; i < l; i++) {
            var temp = GOLBAL_DATA.widgetTemplateList[this.type][i];
            if (temp.id == id) {
                return temp.title;
            }
        }
        return "";
    },
	getViewID: function(name){
        for (var i = 0, l = GOLBAL_DATA.widgetTemplateList[this.type].length; i < l; i++) {
            var temp = GOLBAL_DATA.widgetTemplateList[this.type][i];
            if (temp.title == $.trim(name)){
                return temp.id;
            }
        }
        return null;
    },
    getCustomviewList: function(callback){
        var self = this;
        if (GOLBAL_DATA.widgetTemplateList[this.type].length == 0) {
            GOLBAL_DATA.refreshTemplateListData(this.type, function(o){
                if (typeof callback == 'function') {
                    callback(o);
                }
            });
        }
        else {
            if (typeof callback == 'function') {
                callback(GOLBAL_DATA.widgetTemplateList[self.type]);
            }
        }
        return GOLBAL_DATA.widgetTemplateList[this.type];
    },
    deleteCustomView: function(id, callback){
        var self = this;
        DBHelper.deleteWidgetTemplate(id, function(d){
            if (d) {
                for (var i = 0, l = GOLBAL_DATA.widgetTemplateList[self.type].length; i < l; i++) {
                    var temp = GOLBAL_DATA.widgetTemplateList[self.type][i];
                    if (temp.id == id) {
                        GOLBAL_DATA.widgetTemplateList[self.type].splice(i, 1);
                        break;
                    }
                }
				if(typeof Terminal!='undefined'&&Terminal.getConfig('WatchlistDefaultView')==id){//
					Terminal.setConfig({'WatchlistDefaultView':"-2"});
				}
                delete self.customviewData[id];
                if (typeof callback == 'function') {
                    callback(d);
                }
                Util.message(QS_Lang.text["watchlistcvdelete"]);
            }
        });
    },
    updateCustomView: function(id, colCfg, callback){
        var self = this;
        DBHelper.saveWidgetTemplate(id, {
            cols: this.getMinColumnConfig(colCfg)
            //title: viewName
        }, function(d){
            self.customviewData[id].cols = self.getCompleteColumnConfig(colCfg);
            if (typeof callback == 'function') {
                callback(d);
            }
        });
    },
    addCustomView: function(viewName, colCfg, callback){
        var self = this;
        DBHelper.insertWidgetTemplate(self.type, {
            cols: this.getMinColumnConfig(colCfg),
            title: viewName
        }, function(d){
            var d = $.trim(d);
            if (parseInt(d, 10) > 0) {
                GOLBAL_DATA.widgetTemplateList[self.type].unshift({
                    id: parseInt(d),
                    title: viewName,
                    type: self.type
                });
                self.customviewData[d] = {};
                self.customviewData[d].cols = self.getCompleteColumnConfig(colCfg);
                self.customviewData[d].title = viewName;
            }
            if (typeof callback == 'function') {
                callback(d);
            }
        });
    },
    regCustomview: function(obj, customViewid){
        if (!this.customviewGroup[customViewid]) {
            this.customviewGroup[customViewid] = {};
        }
        if (!this.customviewGroup[customViewid][obj.id]) {
            this.customviewGroup[customViewid][obj.id] = obj;
            this._removeInalidReg(obj.id, customViewid);
        }
    },
    _unregCustomview: function(objid, customViewid){
        if (this.customviewGroup[customViewid] && this.customviewGroup[customViewid][objid]) {
            delete this.customviewGroup[customViewid][objid];
            if ($.isEmptyObject(this.customviewGroup[customViewid])) {
                delete this.customviewGroup[customViewid];
            }
        }
    },
    _removeInalidReg: function(objid, customViewid){
        for (var cvid in this.customviewGroup) {
            if (cvid != customViewid) {
                for (var tobjid in this.customviewGroup[cvid]) {
                    if (objid == tobjid) {
                        this._unregCustomview(tobjid, cvid);
                    }
                }
            }
        }
    },
    sync: function(d,isDel,view){ // when customize view has changed or it is deleted.
        for (var objid in this.customviewGroup[d]) {
            if (this.customviewGroup[d][objid]) {
                if(isDel){ // view delete.
                    if(typeof(this.customviewGroup[d][objid].onViewDelete)=="function"){
                        this.customviewGroup[d][objid].onViewDelete(d);
                    }
                }else{  // view updated.
                    if(typeof(this.customviewGroup[d][objid].onViewUpdate)=="function"){
                        this.customviewGroup[d][objid].onViewUpdate(d,view);
                    }
                }
            }
        }
    }
}
QS_CustomViewManagement = new CustomViewManagement();
//Plugin: custom view
var WatchListCustomView = function(callbacks,config,continerObj){
    this.callback = callbacks||{};
	var qslan=QS_Lang.watchlist;
    this.config = QSPC?QSPC.getConfig(0):{mstartColumn:true,isLPLUser:false};
	$.extend(true,this.config,{isAPI:false},config);
	this.continerObj=continerObj;//only for api,continerObj should include getDom() and getVisible()
    this.viewID = 0;
    this.dataScrollPNleft = null;
    this.dataScrollPNright = null;
    this.defaultViewID="-2";
    this.html = '<div class="bd"><div class="content">' +
    '<div class="colset"><h3>'+qslan["setlabel"]+'</h3><div class="hd clearfix"></div><div class="cols clearfix"><div class="data"></div></div></div>' +
    '<div class="currcols"><h3>'+qslan["viewlabel"]+'</h3><div class="hd"></div><div class="ddwrap"><div class="cols"><div class="data"><ul></ul></div></div></div><h4>'+qslan["dragprompt"]+'</h4></div>' +
    '<div class="viewname"><h3>'+qslan["viewnamelabel"]+'</h3><span class="rtq-chkbox rtq-chkbox_off">'+qslan["defaultlabel"]+'</span><input value="" class="qs-ui-ipt"/></div>' +
    '</div></div>' +
    '<div class="ft"><div class="action"><a class="qs-ui-btn save" href="javascript:void(0)">'+(this.config.isAPI?qslan["confirm"]:qslan["save"])+'</a><a class="qs-ui-btn close" href="javascript:void(0)">'+qslan["close"]+'</a></div></div>';
    this.colSetData = [{
        txt: 'General',
        val: 'gen'
    }, {
        txt: 'Price and Market Data',
        val: 'pri'
    }, this.config.mstartColumn ? {
        txt: 'Morningstar Rating/Grades',
        val: 'mor'
    } : null, {
        txt: 'Portfolio',
        val: 'por'
    }, {
        txt: 'Valuation Measures',
        val: 'val'
    }, {
        txt: 'Dividends',
        val: 'div'
    },{
    	txt: 'Total Return',
        val: 'tot'
	}];
    this.cols = {
        "gen": {
            "Alert": {
                "checked": false
            },
            "os378": {
                "checked": false
            },
            "st153": {
                "checked": false
            },
            "st159": {
                "checked": false
            },
            "Name": {
                "checked": false
            },
            "R/D": {
                "checked": false
            },
            "la03z": {
                "checked": false
            },
            "Symbol": {
                "checked": false
            },
            "Up/Down": {
                "checked": false
            },
            "currency": {
                "checked": false
            },
            "country": {
                "checked": false
            }
        },
        "pri": {
            "LastPrice": {
                "checked": false
            },
            "ClosePrice": {
                "checked": false
            },
            "MiddlePrice": {
                "checked": false
            },
            "Spread": {
                "checked": false
            },
            "LastMarket": {
                "checked": false
            },
            "Chg": {
                "checked": false
            },
            "Chg%": {
                "checked": false
            },
            "os060": {
                "checked": false
            },
            "+/- NAV": {
                "checked": false
            },
            "BidPrice": {
                "checked": false
            },
            "BidSize": {
                "checked": false
            },
            "AskPrice": {
                "checked": false
            },
            "AskSize": {
                "checked": false
            },
            "Volume": {
                "checked": false
            },
            "VWAP": {
                "checked": false
            },
            "st168": {
                "checked": false
            },
            "st169": {
                "checked": false
            },
            "st109": {
                "checked": false
            },
            "st106": {
                "checked": false
            },
            "HighPrice": {
                "checked": false
            },
            "LowPrice": {
                "checked": false
            },
            "Time": {
                "checked": false
            }
        },
        "mor": {
            "st200": {
                "checked": false
            },
            "st202": {
                "checked": false
            },
            "st201": {
                "checked": false
            },
            "st181": {
                "checked": false
            },
            "st206": {
                "checked": false
            }
        },
        "por": {
            "MarketValue": {
                "checked": false
            },
            "P/L": {
                "checked": false
            },
            "P/Lpc": {
                "checked": false
            },
            "NumOfShares": {
                "checked": false
            },
            "PurchaseDate": {
                "checked": false
            },
            "PurchasePrice": {
                "checked": false
            },
            "Comm": {
                "checked": false
            }
        },
        "val": {
            "st198": {
                "checked": false
            },
            "st263": {
                "checked": false
            },
            "st408": {
                "checked": false
            }
        },
        "div": {
            "pm032": {
                "checked": false
            },
            "sta65": {
                "checked": false
            }
        },
		'tot': {
			"pd003":{
				"checked": false
			},
			"pd005":{
				"checked": false
			},
			"pd007":{
				"checked": false
			},
			"pd009":{
				"checked": false
			},
            "pm493":{
                "checked": false
            },
			"pd00d":{
                "checked": false
            },
            "pd014":{
                "checked": false
            },
			"pd00f":{
                "checked": false
            },
			"pd00h":{
                "checked": false
            },
			"pm494":{
                "checked": false
            },
			"pm495":{
                "checked": false
            },
			"pd00b":{
                "checked": false
            }
        }
    };
    this._init();
};
WatchListCustomView.prototype = {
    _checkPermission: function(){
        if (this.config.isLPLUser) {
            this.cols['por']["AccountName"]= {
                "checked": false
            };
            this.cols['por']["Household"]={
                "checked": false
            };
        }
    },
    //find which set the col belong to
    _getSetbyKey: function(colKey){
        for (var set in this.cols) {
            if(this.cols[set][colKey]){
                return set;
            }
        }
        return null;
    },
    _checkIsSelectedAll: function(set){
        for (var i in this.cols[set]) {
            if (!this.cols[set][i].checked) {
                return false;
            }
        }
        this._fnCheckCol(this.colsetCol.find('li[val="0"]'), true);
        return true;
    },
    _addColToCurrentCol: function(colKey){//need update
        if (this.currentCol.find('li[val="' + colKey + '"]').length < 1) {
            var li = document.createElement('li');
            li.colKey = colKey;
            li.setAttribute('val', colKey);
            var txt = QS_WatchlistColumns[colKey].txt;
            if (colKey == 'R/D') {
                txt = 'R/D';
            }
            else 
                if (colKey == 'Alert') {
                    txt = 'Alert';
                }
                else 
                    if (colKey == 'Up/Down') {
                        txt = 'Up/Down';
                    }
            li.innerHTML = '<a href="javascript:void(0)"><em>' + txt + '</em><span>x</span></a>';
            var self = this;
            this.currentCol.find('div.data').children('ul').append(li);
            var drag = new Util.Dragable($(li), {
                onDragStart: function(e, proxy){
                    proxy.html(li.colKey);
                    proxy.dataObj = li.colKey;
                    proxy.$obj = $(li);
                    proxy.selectObj = self;
                },
                onDrag: function(e, proxy){
                
                }
            }, {
                group: "customview"
            });
            var drop = new Util.Dropable($(li), {
                onEnter: function(e, proxy){
                    if (proxy.selectObj && proxy.selectObj == self) {
                        $(li).addClass('customview-drop');
                        //if move to a samilar obj
                    }
                },
                onDrop: function(e, proxy){
                    if (proxy.selectObj && proxy.selectObj == self) {
                        $(li).removeClass('customview-drop');
                        if (proxy.dataObj && proxy.dataObj != li.colKey) {
                            proxy.$obj.insertBefore($(e.target).closest("li"));
                        }
                    }
                },
                onOut: function(e, proxy){
                    if (proxy.selectObj && proxy.selectObj == self) {
                        $(li).removeClass('customview-drop');
                    }
                }
            }, {
                group: "customview"
            });
            if (this.dataScrollPNright) {
                this.dataScrollPNright.reSize(193, 230);
            }
        }
    },
    _fnColsetSelect: function(set){//t:columnsetname v:columnsetnamevalue
        var html = '<ul><li class="rtq-chkbox rtq-chkbox_off" val="0">Select All</li>';
        var chkstr = '';
        for (var i in this.cols[set]) {
            if (this.cols[set][i].checked == true) {
                this._addColToCurrentCol(i);
                chkstr = '';
            }
            else {
                chkstr = ' rtq-chkbox_off';
            }
            html += '<li class="rtq-chkbox' + chkstr + '" val="' + i + '">' + QS_WatchlistColumns[i].txt + '</li>';
        }
        this.pn.find('.colset .cols .data').html(html + '</ul>');
        this._checkIsSelectedAll(set);
        if (this.dataScrollPNleft) {
            this.dataScrollPNleft.reSize(193, 205);
        }
    },
    _fnCheckCol: function(el, Checked){
        var checked = typeof Checked != 'undefined' ? Checked : el.hasClass('rtq-chkbox_off');
        var colKey = el.attr('val');
        el.toggleClass('rtq-chkbox_off', !checked);
        if (colKey == 0) {
            return;
        }
        if (checked) {
            this._addColToCurrentCol(colKey);
        }
        else {
            this._fnCheckCol(this.colsetCol.find('li[val="0"]'), false);
            this.currentCol.find('li[val="' + colKey + '"]').remove();
            if (!this.dataScrollPNright) {
                this.dataScrollPNright = new Util.ScrollPanel(this.pn.find('.currcols .cols .data'), {
                    showX: false
                });
                this.dataScrollPNright.reSize();
            }
            else {
                this.dataScrollPNright.reSize();
            }
        }
        var set = this._getSetbyKey(colKey);
        this.cols[set][colKey].checked = checked;
        this._checkIsSelectedAll(set);
    },
    _createDom: function(){
        this.pn = $('<div class="rtq-wl-ctview">').html(this.html);
        this.colsetCol = this.pn.find('.colset .cols');
        this.currentCol = this.pn.find('.currcols .cols');
        var self = this;
        this.ddlColSet = new Util.DropDownList(this.pn.find('.colset .hd')[0], function(t, v){
            self._fnColsetSelect(v);
        }, this.colSetData, {
            width: 193
        });
		if(this.config.isAPI){
			this.pn.find('.viewname').hide();
		}
		this.defCheckbox = this.pn.find('.viewname .rtq-chkbox');
		this.iptName = this.pn.find('.qs-ui-ipt');
    },
    _bindEvent: function(){
        var self = this;
        self.colsetCol.click(function(e){
            if (e.target.tagName.toLowerCase() == 'li') {
                var el = $(e.target);
                var val = el.attr('val');
                if (val == 0) {
                    var checked = el.hasClass('rtq-chkbox_off');
                    self.colsetCol.find('li').each(function(i){
                        self._fnCheckCol($(this), checked);
                    });
                }
                else {
                    self._fnCheckCol(el);
                }
            }
        });
        this.currentCol.click(function(e){
            var tag = e.target.tagName.toLowerCase();
            e.preventDefault();
            //del col
            if (tag == 'span') {
                var el = $(e.target).parent().parent();
                var colKey = el.attr('val');
                var set = self._getSetbyKey(colKey);
                el.remove();
                if (!self.dataScrollPNright) {
                    self.dataScrollPNright = new Util.ScrollPanel(self.pn.find('.currcols .cols .data'), {
                        showX: false
                    });
                    self.dataScrollPNright.reSize();
                }
                else {
                    self.dataScrollPNright.reSize();
                }
                if (self.colsetCol.find('li[val="' + colKey + '"]').length > 0) {
                    self._fnCheckCol(self.colsetCol.find('li[val="' + colKey + '"]'), false);
                }
                self.cols[set][colKey].checked = false;
            }
        });
        this.defCheckbox.click(function(e){
            $(this).toggleClass('rtq-chkbox_off');
        });
		this.pn.find('.action .close').bind('click', function(e){
			self.hide();
		});
        this.pn.find('.action .save').click(function(e){
			var sltCols = self.currentCol.find('li');
			var name = self.iptName.val();
			if (!self.config.isAPI) {
                if($.trim(name) == ''){
    				Util.alert(QS_Lang.text["watchlistcvinput"]);
    				return;
                }
			}
			if(self.viewID==0&&!self.config.isAPI){//create new view
				if (!QS_Validator.test(name, 'name')) {
					return;
				}
				else if(!QS_CustomViewManagement.checkName(name)){
					Util.alert(QS_Lang.text["watchlistcvtitle"]);//the name is exist
					return;
				}else if (sltCols.length < 1) {
				    Util.alert(QS_Lang.text["watchlistcvselect"]);
                    return;
                }
            }
			var colCfg = [];
			sltCols.each(function(i){
				//only save dataindex and width
				colCfg.push({
					dataIndex: this.colKey,
					width: QS_CustomViewManagement.getColumnAttrFromCache(self.viewID, this.colKey, 'width') //width should be get from cache
				});
			});
			//add the watchlist Del col
			//colCfg.push({});
			var isDefault = !self.defCheckbox.hasClass('rtq-chkbox_off');
            var did = typeof Terminal!='undefined'?Terminal.getConfig('WatchlistDefaultView'):this.defaultViewID;
			if (self.viewID > 0||self.config.isAPI) { //edit
                if(!self.config.isAPI){
    				self.updateView(self.viewID, colCfg,function(sucess,id){
                        if(sucess){
                            Util.message(QS_Lang.text["watchlistcvsuccess"]);
                            if(isDefault^(did==id)){
                                self._updateGlobal(id);
                            }
                            self.hide();
                            if(self.callback.onViewUpdate){
                                self.callback.onViewUpdate(id,name);
                            }
                        }else{
                            //should prompt failed
                        }
                    });
                }else{
                    if(self.callback.onViewUpdate){
                        self.callback.onViewUpdate(colCfg);
                    }
                }
			}else { //add
				self._addView(colCfg, name, function(sucess,id){//create a new 
                    if(sucess){
                        Util.message(QS_Lang.text["watchlistcvsuccess"]);
                        if(isDefault){
                            self._updateGlobal(id);
                        }
                        if(self.callback.onViewCreate){
                            self.callback.onViewCreate(id,name);
                        }
                        self.hide();
                    }else{
                        //should prompt failed
                    }

                });
			}	
		});
    },
    _init: function(){
        this._checkPermission();
        this._createDom();
        var self = this;
		if(this.config.isAPI){
			this.win=this.continerObj.getDom();
			this.win.append(this.pn);
			this._bindEvent();
		}else{
			this.win = new Util.RtqWindow(document.body, {
				windowReady: function(obj){
					obj.setHtml(self.pn);
					self._bindEvent();
				},
				beforeClosed: function(){
				}
			}, {
				title: "Custom View - Untitled",
				top: 100,
				width: 450,
				height: 390,
				resizable: false,
				isGlobal: true,
				hasSettingPanel: false,
				closeAction: 'hide'
			});
			rtqWindowGroup.register(this.win);
		}
		this.hide();
    },
	getVisible:function(){
		return this.continerObj.getVisible();
	},
    _updateGlobal:function(d){
        if(typeof Terminal!='undefined'){
            var viewid=typeof d=='undefined'?this.defaultViewID:d
            Terminal.setConfig({
                WatchlistDefaultView: viewid
            });
        }
    },
	show:function(){
		if(this.config.isAPI){
			this.continerObj.show();
		}else{
			this.win.show();
		}
	},
	hide:function(){
		if(this.config.isAPI){
			this.continerObj.hide();
		}else{
			this.win.hide();
		}
	},
    _addView: function(colCfg, viewName,callback){//create a new view on customview
        var self = this;
        QS_CustomViewManagement.addCustomView(viewName, colCfg, function(d){
            var sucess=(d==null||isNaN(d)||$.trim(d)=='')?false:true;
            if(callback){
                callback(sucess,d);
            }
        });
    },
    deleteView:function(viewid,callback){
        if(parseInt(viewid)<0){
            QS_CustomViewManagement.sync(viewid,true);//is delete customview
            if(callback){
                callback(true,viewid);
            }
        }else{
            var self=this;
            QS_CustomViewManagement.deleteCustomView(viewid, function(d){
                if(d){
                    self._updateGlobal();//modify the default customview
                    QS_CustomViewManagement.sync(viewid,true);//is delete customview
                }
                if(callback){
                    callback(d,viewid);
                }
            });
        }
    },
    updateView:function(viewid,newcols,callback){//exist
        var j=0,dataindex=null;
        for(var i = newcols.length-1; i >=0; i--) {
            dataindex = newcols[i].dataIndex;
            if(dataindex == 'gkey'||dataindex == 'id'){//remove gkey,id, it don't belong to dataColumns.
                newcols.splice(i, 1);
                continue;
            }
            if(dataindex == 'remove'){
                j++;//remove will stay, for cell rearrange
            }
           
        }
        if(newcols.length==j){
            this.deleteView(viewid,callback);
        }else{
            if(parseInt(viewid)<0){
                QS_CustomViewManagement.sync(viewid, false , newcols);
                if(callback){
                    callback(true,viewid);
                }
            }else{
                QS_CustomViewManagement.updateCustomView(viewid, newcols, function(d){
                    if (d) {//sucess
                        QS_CustomViewManagement.sync(viewid, false);
                    }
                    if(callback){
                        callback(d,viewid);
                    }
                });
            }
        }
    },
    _buildData: function(data){
        this.currentCol.find('div.data').children('ul').empty();
        //reset all cols to unchecked
        for (var set in this.cols) {
            for (var i in this.cols[set]) {
                this.cols[set][i].checked = false;
            }
        }
        //add checked cols to currentCol div
        var dataMap, set, colKey;
        for (var j = 0; j < data.length; j++) {
            colKey = data[j].dataIndex;
            set = this._getSetbyKey(colKey);
            if (set) {
                this.cols[set][colKey].checked = true;
                this._addColToCurrentCol(colKey);
            }
        }
    },
    create: function(ViewObj,callback){ //ViewObj {cols:[{dataIndex: 'Name', width: '123'},{}]}
        this.viewID = 0;
        this._buildData(ViewObj ? ViewObj.cols : []);
        this.ddlColSet.selectItemByIndex(0);
        this.iptName.val('').prop({
            "readOnly": false
        });
        this.defCheckbox.removeClass('rtq-chkbox_off'),qslan=QS_Lang.watchlist;
		if(!this.config.isAPI){
			this.win.setTitle(qslan["title"]+" - "+qslan["untitle"]);
		}
        this.show();
        if (!this.dataScrollPNleft) {
            this.dataScrollPNleft = new Util.ScrollPanel(this.pn.find('.colset .cols .data'), {
                showX: false
            });
            this.dataScrollPNleft.reSize(193, 205);
        }
        else {
            this.dataScrollPNleft.reSize(193, 205);
        }
        if (!this.dataScrollPNright) {
            this.dataScrollPNright = new Util.ScrollPanel(this.pn.find('.currcols .cols .data'), {
                showX: false
            });
            this.dataScrollPNright.reSize(193, 230);
        }
        else {
            this.dataScrollPNright.reSize(193, 230);
        }
        this.callback.onViewCreate = callback;
        
    },
    edit: function(ViewObj){//{cols:[{dataIndex: 'Name', width: '123'},{}],id:"242",title:"test"}
        this.viewID = parseInt(ViewObj.id);
        this._buildData(ViewObj.cols);
        this.ddlColSet.selectItemByIndex(0);
        if (typeof ViewObj.title == "undefined") {
            ViewObj.title = QS_CustomViewManagement.getViewName(this.viewID);
        }
        this.iptName.val(ViewObj.title).prop({
            "readOnly": true
        });
        var did = typeof Terminal!='undefined'?Terminal.getConfig('WatchlistDefaultView'):this.defaultViewID;
        if (did == this.viewID) {
			this.defCheckbox.removeClass('rtq-chkbox_off');
        }
        else {
            this.defCheckbox.addClass('rtq-chkbox_off');
        }
		if(!this.config.isAPI){
			this.win.setTitle(QS_Lang.watchlist["title"]+" - "+ViewObj.title);
		}
        this.show();
        if (!this.dataScrollPNleft) {
            this.dataScrollPNleft = new Util.ScrollPanel(this.pn.find('.colset .cols .data'), {
                showX: false
            });
            this.dataScrollPNleft.reSize(193, 205);
        }
        else {
            this.dataScrollPNleft.reSize(193, 205);
        }
        if (!this.dataScrollPNright) {
            this.dataScrollPNright = new Util.ScrollPanel(this.pn.find('.currcols .cols .data'), {
                showX: false
            });
            this.dataScrollPNright.reSize(193, 230);
        }
        else {
            this.dataScrollPNright.reSize(193, 230);
        }
    }
}
var QS_WatchListCustomView = null;
